﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace Forze.SharePointTray
{
    //http://www.csharp-examples.net/restart-windows-service/
    public static class Service
    {
        public static string Status(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            if (service != null)
            {
                return service.Status.ToString();
            }
            else
            {
                return "ServiceNotFound";
            }
        }

        //public static void Start(string serviceName, int timeoutMilliseconds)
        //{
        //    ServiceController service = new ServiceController(serviceName);
        //    try
        //    {
        //        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        //        service.Start();
        //        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        //    }
        //    catch
        //    {
        //        // ...
        //    }
        //}

        //public static void Stop(string serviceName, int timeoutMilliseconds)
        //{
        //    ServiceController service = new ServiceController(serviceName);
        //    try
        //    {
        //        TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

        //        service.Stop();
        //        service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
        //    }
        //    catch
        //    {
        //        // ...
        //    }
        //}

        public static void Restart(string serviceName, int timeoutMilliseconds)
        {
            ServiceController service = new ServiceController(serviceName);
            try
            {
                int millisec1 = Environment.TickCount;
                TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }

                // count the rest of the timeout
                int millisec2 = Environment.TickCount;
                timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
            }
            catch
            {
                // ...
            }
        }

    }
}
